package cn.geminis.manage.service.controller;

import cn.geminis.core.data.query.QueryParameters;
import cn.geminis.manage.core.entity.Role;
import cn.geminis.manage.service.model.FunctionRepository;
import cn.geminis.manage.service.model.RoleRepository;
import cn.geminis.web.logging.LoggingMethod;
import cn.geminis.web.logging.LoggingParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author Allen
 */
@RestController
@RequestMapping("/roles")
public class RoleController {

    @Autowired
    private RoleRepository repository;

    @Autowired
    private FunctionRepository functionRepository;

    @PostMapping
    @PreAuthorize("hasAuthority('manage')")
    public Page<Role> findPage(@RequestBody final QueryParameters queryParameters) {
        return this.repository.findPage(queryParameters);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('manage')")
    public Role get(@PathVariable("id") String id) {
        return repository.where("id", id).findOne().get();
    }

    @PutMapping
    @PreAuthorize("hasAuthority('manage')")
    @LoggingMethod("保存角色")
    public void save(@RequestBody @LoggingParam(value = "名称", field = "name") Role role) {
        this.repository.save(role);
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('manage')")
    @LoggingMethod("删除角色")
    public void delete(@RequestBody @LoggingParam("ID") List<String> ids) {
        ids.forEach(id -> this.repository.deleteById(id));
    }

    @PutMapping("/{id}/function")
    @PreAuthorize("hasAuthority('manage')")
    @LoggingMethod("授权角色功能")
    public void auth(@PathVariable("id") @LoggingParam("ID") String id,
                     @RequestBody @LoggingParam("功能ID") List<String> functionIds) {
        var functions = functionRepository.findAllById(functionIds);
        var role = repository.getOne(id);
        role.setFunctions(new HashSet<>(functions));
        repository.save(role);
    }

    @PutMapping("/{id}/manageRole")
    @PreAuthorize("hasAuthority('manage')")
    @LoggingMethod("设置角色可管理角色")
    public void saveManage(@PathVariable("id") @LoggingParam("ID") String id,
                           @RequestBody @LoggingParam("可管理角色ID") List<String> roleIds) {
        var roles = repository.findAllById(roleIds);
        var role = repository.getOne(id);
        role.setRolesManage(new HashSet<>(roles));
        repository.save(role);
    }

    @GetMapping("/{id}/manageRole")
    @PreAuthorize("hasAuthority('manage')")
    public List<Role> getManage(@PathVariable("id") String id) {
        return new ArrayList<>(
                repository.getOne(id)
                        .getRolesManage());
    }
}
